package com.xzxy.xmlg_backend.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.xzxy.xmlg_backend.entity.*;
import com.xzxy.xmlg_backend.entity.Class;
import com.xzxy.xmlg_backend.service.*;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.stereotype.Service;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;

import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Author: zys
 * @CreateTime: 2025-06-16
 */

@Service
public class FileServiceImpl implements IFileService {

    @Resource
    private IClassService classService;

    @Resource
    private IEmpService empService;

    @Resource
    private IStudentService studentService;

    /**
     * 班级导出
     * @param response
     */
    @Override
    public void exportExcelClass(HttpServletResponse response) {

        List<Class> list = classService.list();

        // 导出，并获取工作簿
        Workbook workbook = ExcelExportUtil.exportExcel(
            new ExportParams(null, "班级信息", ExcelType.XSSF), // 指定为XSSF
            Class.class,
            list
        );

        // 输出
        responseWorkbook(response, workbook, "班级导出.xlsx");
    }

    /**
     * 员工导出
     * @param response
     */
    @Override
    public void exportExcelEmp(HttpServletResponse response) {
        List<Emp> list = empService.list();

        // 导出，并获取工作簿
        Workbook workbook = ExcelExportUtil.exportExcel(
            new ExportParams(null, "员工信息", ExcelType.XSSF), // 指定为XSSF
            Emp.class,
            list
        );

        // 输出
        responseWorkbook(response, workbook, "员工导出.xlsx");
    }

    /**
     * 学员导出
     * @param response
     */
    @Override
    public void exportExcelStudent(HttpServletResponse response) {
        List<Student> list = studentService.list();

        // 导出，并获取工作簿
        Workbook workbook = ExcelExportUtil.exportExcel(
            new ExportParams(null, "学员信息", ExcelType.XSSF), // 指定为XSSF
            Student.class,
            list
        );

        // 输出
        responseWorkbook(response, workbook, "学员导出.xlsx");
    }

    /**
     * 班级模板下载
     * @param response
     */
    @Override
    public void downloadClassTemplate(HttpServletResponse response) {
        File file = new File("file/doc/班级导入模板.xlsx");
        if (!file.exists()) {
            throw new RuntimeException("模板文件不存在");
        }

        try (FileInputStream fis = new FileInputStream(file);
             Workbook workbook = WorkbookFactory.create(fis)) {
            responseWorkbook(response, workbook, "班级导入模板.xlsx");
        } catch (Exception e) {
            throw new RuntimeException("模板下载失败: " + e.getMessage(), e);
        }
    }

    /**
     * 员工模板下载
     * @param response
     */
    @Override
    public void downloadEmpTemplate(HttpServletResponse response) {
        File file = new File("file/doc/员工导入模板.xlsx");
        if (!file.exists()) {
            throw new RuntimeException("模板文件不存在");
        }

        try (FileInputStream fis = new FileInputStream(file);
             Workbook workbook = WorkbookFactory.create(fis)) {
            responseWorkbook(response, workbook, "员工导入模板.xlsx");
        } catch (Exception e) {
            throw new RuntimeException("模板下载失败: " + e.getMessage(), e);
        }
    }

    /**
     * 班级模板下载
     * @param response
     */
    @Override
    public void downloadStudentTemplate(HttpServletResponse response) {
        File file = new File("file/doc/学员导入模板.xlsx");
        if (!file.exists()) {
            throw new RuntimeException("模板文件不存在");
        }

        try (FileInputStream fis = new FileInputStream(file);
             Workbook workbook = WorkbookFactory.create(fis)) {
            responseWorkbook(response, workbook, "学员导入模板.xlsx");
        } catch (Exception e) {
            throw new RuntimeException("模板下载失败: " + e.getMessage(), e);
        }
    }


    /**
     * 导出 Excel
     *
     * @param response
     * @param workbook
     * @param fileName
     */
    private static void responseWorkbook(HttpServletResponse response, Workbook workbook, String fileName) {
        try {
            // 设置ContentType为Excel
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            // 设置Content-Disposition
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName);

            // 写入输出流
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            workbook.close();
            out.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
